/**
 * 获取某一天的前几天或者后几天的日期对象
 * @param { date: number | string | Date, days: number } param date：某一天， days：相差天数
 * @returns {number | string | Date}
 */
 export const getOtherDate = (date: number | string | Date, days: number) => {
  let datetime = +date || Date.now()
  let n = days || 0
  let newDate = new Date(datetime + (n * 24 * 60 * 60 * 1000))
  return newDate
}

/**
 * 时间戳格式化
 * formatTime(1552320000, "yyyy年MM月dd号，hh:mm:ss")
 * @returns {string} 年月日时分秒
 */
 export const formatTime = (time: number | string, predicate: string): string => {
  if (!predicate || !time) return ""
  // let date: Date
  time = Number(time)
  if (String(time).length <= 10) {
    time = time * 1000
  }
  const date: Date = new Date(time)

  const o = {
    "M+": () => date.getMonth() + 1,               // 月
    "d+": () => date.getDate(),                    // 日
    "h+": () => date.getHours(),                   // 小时
    "H+": () => date.getHours() > 12 ? date.getHours() - 12 : date.getHours(),
    "m+": () => date.getMinutes(),                 // 分
    "s+": () => date.getSeconds(),                 // 秒
    "q+": () => Math.floor((date.getMonth() + 3) / 3), // 季度
    "S": () => date.getMilliseconds()             // 毫秒
  }
  let formatPredicate = predicate
  if (/(y+)/.test(predicate)) {
    formatPredicate = formatPredicate.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length))
  }

  type K = keyof typeof o
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(predicate)) {
      const ok = o[k as K]()
      formatPredicate = formatPredicate.replace(RegExp.$1, (RegExp.$1.length === 1) ? ok.toString() : ((`00${ok}`).substr((`${ok}`).length)))
    }
  }
  return formatPredicate
}

/**
 * 获取从昨天开始往前推一段时间对应的日期
 * @param {number} days
 * @returns {string} 返回格式：yyyy-MM-dd
 */
export const getOneDay = (days: number): string => {
  return formatTime(getOtherDate(Date.now(), days).getTime(), 'yyyy-MM-dd');
}
